package cn.zhuzicc.authserverredis.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;

import javax.sql.DataSource;

/**
 * ClassName: AuthorizationServer（授权服务器配置器适配器）
 * Description: 配置客户端相关信息
 * date: 2020/9/28 14:21
 *
 * @author zhuzi
 * @since JDK 1.8
 */
@EnableAuthorizationServer
@Configuration
public class AuthorizationConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    TokenStore tokenStore;
    @Autowired
    DataSource dataSource;

    @Bean
    ClientDetailsService clientDetailsService(){
        return new JdbcClientDetailsService(dataSource);
    }

    /**
     * 配置 Token 的一些基本信息
     * 例如
     * Token 是否支持刷新、
     * Token 的存储位置、
     * Token 的有效期
     * 刷新 Token 的有效期等等
     * @return
     */
    @Bean
    AuthorizationServerTokenServices tokenServices() {
        DefaultTokenServices services = new DefaultTokenServices();
        services.setClientDetailsService(clientDetailsService());
        services.setSupportRefreshToken(true);
        services.setTokenStore(tokenStore);
        return services;
    }

    /**
     * 配置令牌端点的安全约束，也就是这个端点谁能访问，谁不能访问。
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 首先授权服务器会提供一个接口 /oauth/check_token 给资源服务器校验access_token
        // 所以这里配置都可以访问 /oauth/check_token 和表单登录
        security.checkTokenAccess("permitAll()")
                .allowFormAuthenticationForClients();// 允许客户端进行表单身份验证
    }

    /**
     * 用来配置客户端的详细信息
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(clientDetailsService());
       /* clients.inMemory()
                .withClient("javaboy")// id
                .secret(new BCryptPasswordEncoder().encode("123"))// secret
                .resourceIds("res1") // 资源 id
                .authorizedGrantTypes("authorization_code","refresh_token") // 授权类型 授权码模式
                .scopes("all") // 授权范围
                .redirectUris("http://localhost:8082/index.html"); //重定向 uri*/
    }

    /**
     * 配置令牌的访问端点和令牌服务
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // authorizationCodeServices配置授权码的存储存在在内存中
        endpoints.authorizationCodeServices(authorizationCodeServices())
                .tokenServices(tokenServices()); // tokenServices 用来配置令牌的存储，即 access_token 的存储位置，这里我们也先存储在内存中
    }

    @Bean
    AuthorizationCodeServices authorizationCodeServices() {
        return new InMemoryAuthorizationCodeServices();
    }
}